package hdfs;

import java.io.BufferedReader;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test {

    private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
    public static void main(String[] args) {
        String uri = "hdfs://127.0.0.1:9000/";
        Configuration config = new Configuration();
        FileSystem fs = null;
        try {
            fs = FileSystem.get(URI.create(uri), config);
        } catch (IOException e) {
            System.out.println("get url "+ uri+"error" + e);
        }

        // 列出hdfs上/user/fkong/目录下的所有文件和目录
        FileStatus[] statuses = null;
        try {
            statuses = fs.listStatus(new Path("/user/input"));
        } catch (Exception e) {
            System.out.println("listStatus  /user/input error" + e);
        }
        for (FileStatus status : statuses) {
            System.out.println(status + "" );
        }

        // 在hdfs的/user/fkong目录下创建一个文件，并写入一行文本
        FSDataOutputStream os = null;
        try {
            os = fs.create(new Path("/user/input/test.log"));
            os.write("Hello World!".getBytes());
            os.flush();
        } catch (Exception e) {
            System.out.println("create /user/input/test.log error " + e);
        }
        try {
            os.flush();
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            System.out.println("close /user/input/test.log error " + e);
        }

        // 显示在hdfs的/user/fkong下指定文件的内容
        FilterInputStream is = null;
        BufferedReader bufferedReader = null;
        InputStreamReader isr = null;
        try {
            is = fs.open(new Path("/user/input/test.log"));
            isr = new InputStreamReader(is, "UTF-8");
            bufferedReader = new BufferedReader(isr);
            String content = null;
            while ((content = bufferedReader.readLine()) != null) {
                System.out.println("content:" + content);
            }
        } catch (Exception e) {
            System.out.println("open /user/input/test.log error " + e);
        }
        System.out.println("成功");
    }
}
